package com.sky.cqculture.service.impl;

import com.sky.cqculture.Mapper.FavoriteMapper;
import com.sky.cqculture.pojo.Favorite;
import com.sky.cqculture.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {
    
    @Autowired
    private FavoriteMapper favoriteMapper;
    
    @Override
    public void toggleFavorite(Integer userId, Integer heritageId, Integer status) {
        // 检查是否已存在收藏记录
        Favorite existingFavorite = favoriteMapper.findByUserAndHeritage(userId, heritageId);
        
        if (status == 1) {
            // 收藏操作
            if (existingFavorite == null) {
                // 创建新的收藏记录
                Favorite favorite = new Favorite();
                favorite.setUserId(userId);
                favorite.setHeritageId(heritageId);
                favorite.setCreateTime(new Date());
                favorite.setStatus(1);
                favoriteMapper.insert(favorite);
            } else if (existingFavorite.getStatus() == 0) {
                // 更新已有记录的状态为收藏
                existingFavorite.setStatus(1);
                favoriteMapper.update(existingFavorite);
            }
        } else {
            // 取消收藏操作
            if (existingFavorite != null) {
                if (existingFavorite.getStatus() == 1) {
                    // 更新已有记录的状态为取消收藏
                    existingFavorite.setStatus(0);
                    favoriteMapper.update(existingFavorite);
                }
            }
        }
    }
    
    @Override
    public boolean isFavorite(Integer userId, Integer heritageId) {
        Favorite favorite = favoriteMapper.findByUserAndHeritage(userId, heritageId);
        return favorite != null && favorite.getStatus() == 1;
    }
    
    @Override
    public List<Favorite> getUserFavorites(Integer userId) {
        return favoriteMapper.findByUserId(userId);
    }
}